package com.bitBusy.manageyourriches.activity;

import java.io.File;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bitBusy.manageyourriches.R;
import com.bitBusy.manageyourriches.alarmSystem.AlarmManagement;
import com.bitBusy.manageyourriches.database.contactClasses.PaymentReminder;
import com.bitBusy.manageyourriches.database.managers.DatabaseInteractor;
import com.bitBusy.manageyourriches.database.managers.DateTimeManager;
import com.bitBusy.manageyourriches.emailManagement.Postman;
import com.bitBusy.manageyourriches.utilityClasses.display.DisplayMessages;
import com.bitBusy.manageyourriches.utilityClasses.filehandlers.DataExportRequestors;
import com.bitBusy.manageyourriches.utilityClasses.filehandlers.ReportFileBuilder;
import com.bitBusy.manageyourriches.utilityClasses.navigation.ActionBarChoice;

public class ExportDataActivity extends Activity implements DataExportRequestors{ 

	private static final int NUMOFDAYSINWEEK = 7;
	
	private static final int HOUROFALARM = 7;
	
	private static final int MINOFALARM = 0;
	
	private static final int RECURRENT = 1;
	
	private static final int RECURRENTWEEKLY = 0;
	
	private static final int RECURRENTMONTHLY = 1;
	
	private static final int FIRSTDAYOFMONTH = 1;

	private static final String ALARMSET = "Next scheduled export set for: ";
	



	/** flag to indicate export period*/
	private boolean myOneTimeExport = true;
	
	/** flag to indicate weekly export*/
	private boolean myWeeklyExport = true;
	
	private DatabaseInteractor myDBInteractor;

	private String myEmail;
	
		@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_export_data);
		myDBInteractor = new DatabaseInteractor(this);

	}
	public void viewScheduled(View the_view)
    {
    	Intent intent = new Intent(this, ScheduledExportsActivity.class);
    	startActivity(intent);
    }
	public void exportOnce(View the_view)
	{
		myOneTimeExport = true;
		setRecurrentViews(View.INVISIBLE);	
	}

	/**
	 * @param visible
	 */
	private void setRecurrentViews(int the_visibility) {
		TextView frequencyPrompt = (TextView) findViewById(R.id.exportDataActivity_frequencyPrompt);
		frequencyPrompt.setVisibility(the_visibility);
		RadioGroup frequencyOptions = (RadioGroup) findViewById(R.id.exportDataActivity_frequencyExportOptions);
		frequencyOptions.setVisibility(the_visibility);
	
	}

	public void exportRecurrent(View the_view)
	{
		myOneTimeExport = false;
		setRecurrentViews(View.VISIBLE);	

	}
	
	public void exportWeekly(View the_view)
	{
		myWeeklyExport = true;
	}
	public void exportMonthly(View the_view)
	{
		myWeeklyExport = false;
	}
	
	public void export(View the_view)
	{
		myEmail = getEmail();
			if (Postman.checkEmail(myEmail))
		{
			if (myOneTimeExport)
			{
				requestReport();
			}
			else
			{
				scheduleReport();
			}
		}
		else
		{
			DisplayMessages.displayUserError(this, Postman.EMAILERROR);
		}
	}
		/**
	 * 
	 */
	private void scheduleReport() { 
		PaymentReminder reminder;
		if (myWeeklyExport)
		{
			reminder = getNextWeeklyReminder();
		}
		else
		{
			reminder = getNextMonthlyReminder();
		}
		if (AlarmManagement.setAlarm(reminder))
		{
			Toast.makeText(this, new StringBuilder(ALARMSET).append(DateTimeManager.getDate(reminder.getDay(), 
					reminder.getMonth()+1, reminder.getYear())), Toast.LENGTH_LONG).show();
	        refresh();

		}
		else
		{
		DisplayMessages.displayUserError(this, Postman.NOTSET);
		}
	}

		/**
		 * 
		 */
		private void refresh() {
			EditText emailText = (EditText)findViewById(R.id.exportDataActivity_emailEditText);
			emailText.setText("");
			RadioButton once = (RadioButton)findViewById(R.id.exportDataaActivity_oneTime);
			once.setChecked(true);
			myOneTimeExport = true;
			setRecurrentViews(View.INVISIBLE);

		}
		/**
		 * @return
		 */
		private PaymentReminder getNextMonthlyReminder() {
			Calendar date = getNextMonthDate();
			return new PaymentReminder(date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.MONTH), 
					date.get(Calendar.YEAR),HOUROFALARM, MINOFALARM, null, RECURRENT, RECURRENTMONTHLY, myEmail, (int) System.currentTimeMillis() ); 	

		}

		/**
		 * @return
		 */
		private Calendar getNextMonthDate() {
			Calendar date = Calendar.getInstance();
			int nowMonth = date.get(Calendar.MONTH);
			int nowYear = date.get(Calendar.YEAR);
			nowMonth = (nowMonth + 1); 
			int year = nowMonth>11? nowYear + 1:nowYear;
			int month = nowMonth>11?1:nowMonth;
			date.set(Calendar.MONTH, month);
			date.set(Calendar.DAY_OF_MONTH, FIRSTDAYOFMONTH);
			date.set(Calendar.YEAR, year);
			System.out.println("Date " + date.toString());
			return date;
		
		}

		/**
		 * @return
		 */
		private PaymentReminder getNextWeeklyReminder() {
			Calendar date = getNextMondayDate();
			return new PaymentReminder(date.get(Calendar.DAY_OF_MONTH), date.get(Calendar.MONTH), 
					date.get(Calendar.YEAR),HOUROFALARM, MINOFALARM, null, RECURRENT, RECURRENTWEEKLY,myEmail, (int) System.currentTimeMillis()); 	
		}
		/**
		 * @return
		 */
		private Calendar getNextMondayDate() {
			Calendar date = Calendar.getInstance();
			int today = date.get(Calendar.DAY_OF_WEEK);
			int diff = Calendar.MONDAY - today;
			if (today < 2)
			{
				date.add(Calendar.DAY_OF_WEEK, diff);
			}
			else
			{
				date.add(Calendar.DAY_OF_WEEK, NUMOFDAYSINWEEK + diff);
			}
			return date;
		}

		/**
	 * 
	 */
	private void requestReport() {
		ReportFileBuilder fileBuilder = new ReportFileBuilder(this);
		fileBuilder.registerRequestors(this);
		myDBInteractor.getReportTillDate(fileBuilder);
	}

		/**
		 * @param b
		 */
		

		/**
	 * @param email
	 * @param reportTillDate
	 */
	/*private Postman.EMAILSENTCODES sendMail(String the_emailAddress) {
		return Postman.send(the_emailAddress, );		
	}

		/**
	 * @return
	 */
	private String getEmail() {
		EditText emailText = (EditText)findViewById(R.id.exportDataActivity_emailEditText);
		return emailText.getText().toString();
	}


	@Override
	  public boolean onCreateOptionsMenu(Menu the_menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.actionbar_menu, the_menu);
	    return true;
	  }
	 @Override
	  public boolean onOptionsItemSelected(MenuItem the_item) {
	    ActionBarChoice.choiceMade(this, the_item.getItemId());

	    return true;
	  }
	 
	 /* (non-Javadoc)
		 * @see com.bitBusy.manageyourriches.utilityClasses.filehandlers.DataExportRequestors#acceptFile(java.io.File)
		 */
		@Override
		public void acceptFile(File the_file) {
			if (the_file != null)
			{
				Postman.EMAILSENTCODES postAckCode = Postman.send(getEmail(), the_file);
				if(postAckCode.equals(Postman.EMAILSENTCODES.SUCCESS))
				{
					Toast.makeText(getApplicationContext(), Postman.EMAILSENT, Toast.LENGTH_LONG).show();
				}
				else if(postAckCode.equals(Postman.EMAILSENTCODES.FAILUREEMAILADDRESS))
				{
					DisplayMessages.displayUserError(this,Postman.EMAILERROR);
				}
				else if(postAckCode.equals(Postman.EMAILSENTCODES.FAILURESYSEM))
				{
					DisplayMessages.displayInternalError(this, Postman.SYSTEMFAIL);
				}
			}
			
		}
}
